package zhihui.mobile.presenter.address;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import zhihui.mobile.R;
import zhihui.mobile.bean.address.CommunityInfo;
import zhihui.mobile.bean.address.login.Area;
import zhihui.mobile.bean.address.login.City;
import zhihui.mobile.bean.address.login.Province;
import zhihui.mobile.config.Config;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.address.NewAddressManager;
import zhihui.mobile.ui.IView;

/**
 * Created by 张公铭 on 2017/7/5 0005.
 */

public class AddressPresenter implements IAddressContract.IAddressPresenter
{
    private Logger logger = Logger.getLogger(AddressPresenter.class);
    private IAddressContract.IAddressView addressView;
    private Context mContext;
    private List<CommunityInfo> mList = new ArrayList<>();

    @Override
    public void init(IView view, Context context)
    {
        addressView = (IAddressContract.IAddressView) view;
        mContext = context;
    }

    @Override
    public void onResume()
    {
        Gson gson = new Gson();
    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onPause()
    {

    }

    @Override
    public void onStop()
    {

    }

    @Override
    public void onDestroy()
    {

    }

    private void showDialog()
    {
        NewAddressManager manager = NewAddressManager.getInstance();
        Province province = manager.getLastProvince();
        int proPosition = manager.proPosition;
        if (province == null)
        {
            province = manager.getmAddressList().get(0);
            proPosition = 0;
        }
        City city = manager.getLastCity();
        int cityPosition = manager.cityPosition;
        if (city == null)
        {
            city = province.getCity().get(0);
            cityPosition = 0;
        }
        Area area = manager.getLastArea();
        int areaPosition = manager.areaPosition;
        if (area == null)
        {
            area = city.getArea().get(0);
            areaPosition = 0;
        }
        addressView.showAreaDialog(province, proPosition, city, cityPosition, area, areaPosition);
    }

    @Override
    public void initArea()
    {
        if (NewAddressManager.getInstance().getmAddressList() != null && NewAddressManager.getInstance().getmAddressList().size() > 0)
        {
            showDialog();
        } else
        {
            //new AreaLoadTask().execute();
            addressView.showLoading();
            NewAddressManager.getInstance().getCityInfoByUser(new IHttpCallBackListener()
            {
                @Override
                public void success(JSONObject result)
                {
                    addressView.hindLoading();
                    Gson gson = new Gson();
                    try
                    {
                        List<zhihui.mobile.bean.address.login.Province> list = gson.fromJson(result.getJSONArray("data").toString(),
                                new TypeToken<List<zhihui.mobile.bean.address.login.Province>>(){}.getType());
                        NewAddressManager.getInstance().setmAddressList(list);
                        showDialog();
                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                        addressView.showMessage(mContext.getString(R.string.json_error));
                    }
                }

                @Override
                public void failed(String message)
                {
                    addressView.hindLoading();
                    addressView.showMessage(message);
                }
            });

        }
    }

    @Override
    public List<Province> getProvinceList()
    {
        return NewAddressManager.getInstance().getmAddressList();
    }

    @Override
    public void updateCity(Province province, int position)
    {
        NewAddressManager.getInstance().setLastProvince(province);
        NewAddressManager.getInstance().proPosition = position;
        addressView.refreshCity(province.getCity());
    }

    @Override
    public void updateArea(City city, int position)
    {
        NewAddressManager.getInstance().setLastCity(city);
        NewAddressManager.getInstance().cityPosition = position;
        addressView.refreshArea(city.getArea());
    }

    @Override
    public void getCommunityList(Area area, int position)
    {
        NewAddressManager.getInstance().setLastArea(area);
        NewAddressManager.getInstance().areaPosition = position;
        addressView.closeDialog(area.getName_f());
        addressView.showLoading();
        NewAddressManager.getInstance().getCommunityList(area, new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                addressView.hindLoading();
                try
                {
                    logger.debug("getCommunityList result:" + result.toString());
                    String state = result.getString("state");
                    String msg = result.getString("msg");
                    if (state.equals(Config.SUCCESS))
                    {
                        Gson gson = new Gson();
                        JSONArray array = result.getJSONArray("data");
                        List<CommunityInfo> list = gson.fromJson(array.toString(), new TypeToken<List<CommunityInfo>>()
                        {
                        }.getType());
                        mList.clear();
                        mList.addAll(list);
                        addressView.refreshCommunityList(mList);
                    } else
                    {
                        addressView.showMessage(msg);
                    }
                } catch (JSONException e)
                {
                    logger.error("AddressPresenter getCommunityList json error:" + e.getMessage());
                    e.printStackTrace();
                    addressView.showMessage("解析数据错误！" + e.getMessage());
                }
            }

            @Override
            public void failed(String message)
            {
                addressView.hindLoading();
                addressView.showMessage(message);
            }
        });
    }

    @Override
    public void clear()
    {
        NewAddressManager.getInstance().clear();
    }

    @Override
    public List<CommunityInfo> getCurComminityList()
    {
        return mList;
    }

    @Override
    public void searchCommunity(String text)
    {
        List<CommunityInfo> tempList = new ArrayList<>();
        for (CommunityInfo communityInfo : mList)
        {
            if (communityInfo.getName().contains(text))
            {
                tempList.add(communityInfo);
            }
        }
        if (tempList.size() > 0)
        {
            addressView.refreshCommunityList(tempList);
        }
    }

//    class AreaLoadTask extends AsyncTask<Void, Void, Boolean>
//    {
//        @Override
//        protected void onPreExecute()
//        {
//
//            addressView.showLoading();
//        }
//
//        @Override
//        protected Boolean doInBackground(Void... params)
//        {
//            Boolean result = new Boolean(false);
//
//            try
//            {
//                InputStream is = mContext.getAssets().open("area.json");
//                byte[] bytes = new byte[is.available()];
//                is.read(bytes);
//                is.close();
//                String json = new String(bytes);
//                Gson gson = new Gson();
//                List<Province> list = gson.fromJson(json, new TypeToken<List<Province>>()
//                {
//                }.getType());
//                NewAddressManager.getInstance().setmAddressList(list);
//                result = true;
//            } catch (Exception e)
//            {
//                result = false;
//                e.printStackTrace();
//                logger.error("解析地区文件错误：" + e.getMessage());
//            }
//            return result;
//        }
//
//        @Override
//        protected void onPostExecute(Boolean bool)
//        {
//            addressView.hindLoading();
//            if (bool)
//            {
//                showDialog();
//            } else
//            {
//                addressView.showMessage("获取地区信息失败！");
//            }
//        }
//    }
}
